import 'dart:convert';

import 'package:chat/common/model/UserMessageModel.dart';
import 'package:chat/common/service/websocket/BaseWebSocketService%20.dart';
import 'package:chat/pages/chat/chat/index.dart';
import 'package:get/get.dart';

import '../../../pages/chat/chatDetail/controller.dart';

class ChatSocketService extends BaseWebSocketService {
  ChatSocketService(int userId) : super("ws://172.20.10.4:2025/websocket/chat", userId);

  @override
  void onMessage(msg) {
    print("💬 [ChatSocket] 收到消息: $msg");

    final data = jsonDecode(msg);
    UserMessageModel userMessage = UserMessageModel.fromJson(data);

    // ✅ 如果 ChatdetailController 已经存在（用户正在聊天详情页）
    if (Get.isRegistered<ChatdetailController>()) {
      Get.find<ChatdetailController>().receiveMessage(userMessage);
    } else {
      // TODO 这里用于刷新聊天列表
      if (Get.isRegistered<ChatController>()) {
        Get.find<ChatController>().receiveMessage(userMessage);
      }
    }
  }
}
